package com.chookss.home.gallery;

import android.content.Context;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.EditorInfo;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.recyclerview.widget.SimpleItemAnimator;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.viewholder.BaseViewHolder;
import com.chookss.R;
import com.chookss.Urls;
import com.chookss.base.BaseViewHolderEx;
import com.chookss.home.entity.GalleryTagEntity;
import com.chookss.tiku.view.FlowLayout;
import com.chookss.tools.MyEvent;
import com.chookss.tools.MyToast;
import com.chookss.tools.SignUtils2;
import com.chookss.tools.Utils;
import com.chookss.tools.okgoconfig.MyHttpRequest;
import com.chookss.tools.okgoconfig.callback.ObserverCallback;
import com.chookss.tools.okgoconfig.model.LzyResponse;
import com.google.gson.reflect.TypeToken;
import com.lvgroup.hospital.base.BaseAct;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.constant.RefreshState;
import com.scwang.smartrefresh.layout.listener.OnLoadMoreListener;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;

import org.greenrobot.eventbus.EventBus;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import io.reactivex.annotations.NonNull;
import io.reactivex.annotations.Nullable;

public class GalleryMultipleChoiceLabelActivity extends BaseAct {


    @BindView(R.id.common_title_txt)
    TextView commonTitleTxt;
    @BindView(R.id.common_right_txt)
    TextView commonRightTxt;
    @BindView(R.id.edContent)
    EditText edContent;
    @BindView(R.id.tvNum)
    TextView tvNum;
    @BindView(R.id.flowLayout)
    FlowLayout flowLayout;
    @BindView(R.id.rvView)
    RecyclerView rvView;
    @BindView(R.id.srlView)
    SmartRefreshLayout srlView;
    @BindView(R.id.ivNone)
    ImageView ivNone;
    @BindView(R.id.tvNone)
    TextView tvNone;
    @BindView(R.id.tvSearch)
    TextView tvSearch;
    @BindView(R.id.llNone)
    LinearLayout llNone;
    @BindView(R.id.llBg)
    LinearLayout llBg;
    private LabelAdapter adapter;
    private List<GalleryTagEntity> list = new ArrayList<>();
    private String searchKey = "";
    private int currentPage = 1;
    private boolean isEnd = false;//是否到底
    private List<GalleryTagEntity> selectList = new ArrayList<>();
    private FlowAdapter selectAdapter;
    private String tagName = "";
    private String tagCodes = "";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // TODO: add setContentView(...) invocation
        setContentView(R.layout.activity_gallery_multiple_choice_label);
        ButterKnife.bind(this);
    }

    @Override
    public void initData() {
        initState();
        tagName = getIntent().getStringExtra("tagName");
        tagCodes = getIntent().getStringExtra("tagCodes");
        commonTitleTxt.setText("标签");
        commonRightTxt.setText("保存");
        commonRightTxt.setVisibility(View.VISIBLE);
        commonRightTxt.setTextColor(getResources().getColor(R.color.main_color));
        ivNone.setBackgroundResource(R.drawable.icon_default_no_common);
        tvNone.setText("暂无标签");
        rvView.setLayoutManager(new LinearLayoutManager(this, LinearLayoutManager
                .VERTICAL, false));
        adapter = new LabelAdapter(R.layout.item_gallery_multiple_choice_label, this, list);
        rvView.setAdapter(adapter);
        ((SimpleItemAnimator) rvView.getItemAnimator()).setSupportsChangeAnimations(false);
        srlView.setOnLoadMoreListener(new OnLoadMoreListener() {
            @Override
            public void onLoadMore(@NonNull RefreshLayout refreshLayout) {
                if (isEnd) {//has next page
                    MyToast.show("没有更多数据了");
                    loadEnd();
                } else {
                    currentPage++;
                    getData();
                }
            }
        });
        srlView.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(RefreshLayout refreshLayout) {
                currentPage = 1;
                isEnd = false;
                getData();
            }
        });
        srlView.autoRefresh();
        edContent.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
                if (actionId == EditorInfo.IME_ACTION_SEARCH) {   // 按下完成按钮，这里和上面imeOptions对应
                    if (!Utils.isNull(v.getText().toString())) {
                        searchKey = v.getText().toString();
                        tagCodes="";
                        tagName="";
                        Utils.hideInputKeyboard(GalleryMultipleChoiceLabelActivity.this, edContent);
                        srlView.autoRefresh();
                        return false;   //返回true，保留软键盘。false，隐藏软键盘
                    } else {
                        MyToast.show("请输入搜索标签");
                    }
                }
                return true;   //返回true，保留软键盘。false，隐藏软键盘
            }
        });
        edContent.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                if (Utils.isNull(s.toString())) {
                    tvSearch.setVisibility(View.GONE);
                } else {
                    tvSearch.setVisibility(View.VISIBLE);
                }
            }
        });
    }

    private void getData() {
        Map<String, String> allmap = new HashMap<>();
        allmap.put("pageNum", currentPage + "");
        allmap.put("pageSize", "50");
        if (!Utils.isNull(searchKey)) {
            allmap.put("tagName", searchKey);
        }
        MyHttpRequest.getDefault().getRequest(new TypeToken<LzyResponse<List<GalleryTagEntity>>>() {
        }.getType(), null, Urls.getTagList, SignUtils2.makeSignStr(allmap), false, new ObserverCallback<List<GalleryTagEntity>>() {
            @Override
            public void onSuccess(List<GalleryTagEntity> data) {
                if (currentPage == 1) {
                    list.clear();
                    adapter.notifyDataSetChanged();
                }
                if (srlView == null || llNone == null) {
                    return;
                }
                int oldIndex = list.size();
                if (data != null && data.size() > 0) {
                    List<GalleryTagEntity> acceptList = data;
                    if (data.size() < 50) {
                        isEnd = true;
                    }
                    if (currentPage == 1 && Utils.isNull(searchKey)) {
                        GalleryTagEntity galleryTagEntity = new GalleryTagEntity();
                        galleryTagEntity.setTagName("全部");
                        galleryTagEntity.setTagCode("");
                        galleryTagEntity.setIndex(0);
                        if (Utils.isNull(tagCodes) && !Utils.isNull(tagName)) {
                            //选择的全部
                            galleryTagEntity.setSelect(true);

                            list.add(galleryTagEntity);
                            list.addAll(acceptList);
                            addTag(galleryTagEntity);
                        } else {
                            galleryTagEntity.setSelect(false);
                            list.add(galleryTagEntity);
                            if(Utils.isNull(tagCodes)){
                                list.addAll(acceptList);
                            }else{
                                String[] codes = tagCodes.split(",");
                                for (int i = 0; i < acceptList.size(); i++) {
                                    for (int j = 0; j < codes.length; j++) {
                                        if (codes[j].equals(acceptList.get(i).getTagCode())) {
                                            acceptList.get(i).setSelect(true);
                                            acceptList.get(i).setIndex(list.size());
                                            addTag( acceptList.get(i));
                                        }
                                    }
                                    list.add(acceptList.get(i));
                                }
                            }
                        }
                    }

                    if (!Utils.isNull(searchKey)) {
                        for (int i = 0; i < acceptList.size(); i++) {
                            for (int j = 0; j < selectList.size(); j++) {
                                if (selectList.get(j).getTagCode().equals(acceptList.get(i).getTagCode())) {
                                    acceptList.get(i).setSelect(true);
                                    acceptList.get(i).setIndex(list.size());
                                    selectList.get(j).setIndex(list.size());
                                }
                            }
                            list.add(acceptList.get(i));
                        }
                    } else {
                        if(currentPage>=2){
                            if(Utils.isNull(tagCodes)){
                                list.addAll(acceptList);
                            }else{
                                String[] codes = tagCodes.split(",");
                                for (int i = 0; i < acceptList.size(); i++) {
                                    for (int j = 0; j < codes.length; j++) {
                                        if (codes[j].equals(acceptList.get(i).getTagCode())) {
                                            acceptList.get(i).setSelect(true);
                                            acceptList.get(i).setIndex(list.size());
                                            addTag( acceptList.get(i));
                                        }
                                    }
                                    list.add(acceptList.get(i));
                                }
                            }
                        }

                    }
                    if (currentPage == 1) {
                        adapter.notifyDataSetChanged();
                    } else {
                        adapter.notifyItemRangeChanged(oldIndex, data.size());
                    }
                    srlView.setVisibility(View.VISIBLE);
                    llNone.setVisibility(View.GONE);
                } else {
                    isEnd = true;
                    if (list.size() == 0) {
                        srlView.setVisibility(View.GONE);
                        llNone.setVisibility(View.VISIBLE);
                    }
                }
                loadEnd();
            }

            @Override
            public void onError(String errorMsg) {
                loadEnd();
                MyToast.show(Utils.onErrorTips(errorMsg));
            }
        });
    }

    @OnClick({R.id.common_title_back, R.id.tvSearch, R.id.common_right_txt})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.common_title_back:
                finish();
                break;
            case R.id.common_right_txt:
                if (selectList.size() == 0) {
                    MyToast.show("请选择至少一个标签");
                } else {
                    tagName = "";
                    tagCodes = "";
                    for (int i = 0; i < selectList.size(); i++) {
                        if (Utils.isNull(tagName)) {
                            tagName = tagName + selectList.get(i).getTagName();
                            tagCodes = tagCodes + selectList.get(i).getTagCode();
                        } else {
                            tagName = tagName + "," + selectList.get(i).getTagName();
                            tagCodes = tagCodes + "," + selectList.get(i).getTagCode();
                        }
                    }
                    Map<String, String> map = new HashMap<>();
                    map.put("tagName", tagName);
                    map.put("tagCodes", tagCodes);
                    EventBus.getDefault().post(new MyEvent(map));
                    finish();
                }
                break;
            case R.id.tvSearch:
                searchKey = edContent.getText().toString();
                if (edContent != null) {
                    Utils.hideInputKeyboard(this, edContent);
                }
                tagCodes="";
                tagName="";
                srlView.autoRefresh();
                break;
        }
    }

    class LabelAdapter extends BaseQuickAdapter<GalleryTagEntity, BaseViewHolderEx> {
        private Context context;

        public LabelAdapter(int layoutResId, Context context, @Nullable List<GalleryTagEntity> data) {
            super(layoutResId, data);
            this.context = context;
        }

        @Override
        protected void convert(BaseViewHolderEx helper, GalleryTagEntity item) {
            ImageView ivType = helper.getView(R.id.ivType);
            TextView tvTitle = helper.getView(R.id.tvTitle);
            tvTitle.setText(item.getTagName() + "");
            if (item.isSelect()) {
                ivType.setVisibility(View.VISIBLE);
            } else {
                ivType.setVisibility(View.GONE);
            }
            helper.getItemView().setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    if (item.isSelect()) {
                        removeTag(item);
                        item.setSelect(false);
                    } else {
                        item.setSelect(true);
                        item.setIndex(helper.getItemPosition());
                        addTag(item);
                    }
                    adapter.notifyItemChanged(helper.getItemPosition());
                }
            });
        }

    }

    class FlowAdapter extends FlowLayout.Adapter<FlowAdapter.FlowViewHolder> {

        private static final String TAG = "FlowAdapter";

        private Context mContext;
        private List<GalleryTagEntity> mContentList;

        public FlowAdapter(Context mContext, List<GalleryTagEntity> mContentList) {
            this.mContext = mContext;
            this.mContentList = mContentList;
        }

        @Override
        public FlowAdapter.FlowViewHolder onCreateViewHolder(ViewGroup parent) {
            View view = LayoutInflater.from(mContext).inflate(R.layout.item_gallery_choice_city_title, parent, false);
//            // 给 View 设置 margin
            ViewGroup.MarginLayoutParams mlp = new ViewGroup.MarginLayoutParams(view.getLayoutParams());
            mlp.setMargins(0, 0, Utils.dip2px(mContext, 12), Utils.dip2px(mContext, 12));
            view.setLayoutParams(mlp);

            return new FlowAdapter.FlowViewHolder(view);
        }

        @Override
        public void onBindViewHolder(FlowAdapter.FlowViewHolder holder, int position) {
            holder.tvTitle.setText(mContentList.get(position).getTagName());
            holder.llDelete.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    removeTag(mContentList.get(position));
                }
            });
        }

        @Override
        public int getItemCount() {
            return mContentList.size();
        }

        class FlowViewHolder extends FlowLayout.ViewHolder {
            TextView tvTitle;
            LinearLayout llDelete;

            public FlowViewHolder(View itemView) {
                super(itemView);
                tvTitle = itemView.findViewById(R.id.tvTitle);
                llDelete = itemView.findViewById(R.id.llDelete);
            }
        }
    }

    private void addTag(GalleryTagEntity galleryTagEntity) {
        // 设置 Adapter
        if (flowLayout == null) {
            return;
        }
        if (selectList.size() == 0) {
            selectList.add(galleryTagEntity);
        } else {
            selectList.add(0, galleryTagEntity);
        }
        if (galleryTagEntity.getIndex() == 0) {
            //选择是全部，去除当前其余选择
            for (int i = 0; i < selectList.size(); i++) {
                if (selectList.get(i).getIndex() != 0) {
                    list.get(selectList.get(i).getIndex()).setSelect(false);
                    adapter.notifyItemChanged(selectList.get(i).getIndex());
                    selectList.remove(i);
                    i--;
                }
            }
        } else {
            //选择的是其他，要去除全部
            for (int i = 0; i < selectList.size(); i++) {
                if (selectList.get(i).getIndex() == 0) {
                    list.get(0).setSelect(false);
                    adapter.notifyItemChanged(0);
                    selectList.remove(i);
                    i--;
                }
            }
        }
        if (selectList.size() > 4) {
            removeTag(selectList.get(4));
        } else {
            flowLayout.setVisibility(View.VISIBLE);
            selectAdapter = new FlowAdapter(this, selectList);
            flowLayout.setAdapter(selectAdapter);
            tvNum.setText(selectList.size() + "/4");
        }

    }

    private void removeTag(GalleryTagEntity galleryTagEntity) {
        // 设置 Adapter
        if (flowLayout == null) {
            return;
        }
        for (int i = 0; i < selectList.size(); i++) {
            if (selectList.get(i).getTagCode().equals(galleryTagEntity.getTagCode())) {
                for (int j = 0; j < list.size(); j++) {
                    if (list.get(j).getTagCode().equals(galleryTagEntity.getTagCode())) {
                        list.get(selectList.get(i).getIndex()).setSelect(false);
                        adapter.notifyItemChanged(selectList.get(i).getIndex());
                    }
                }
                selectList.remove(i);
                i--;
            }

        }
        // 设置 Adapter
        if (selectList.size() > 0) {
            flowLayout.setVisibility(View.VISIBLE);
            selectAdapter = new FlowAdapter(this, selectList);
            flowLayout.setAdapter(selectAdapter);
        } else {
            flowLayout.setVisibility(View.GONE);
        }
        tvNum.setText(selectList.size() + "/4");
    }

    private void loadEnd() {
        if (null != srlView && srlView.getState() == RefreshState.Refreshing)
            srlView.finishRefresh(true);
        if (null != srlView && srlView.getState() == RefreshState.Loading)
            srlView.finishLoadMore(true);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (edContent != null) {
            Utils.hideInputKeyboard(this, edContent);
        }
    }
}
